using System.IO;
using System.Xml;
using com.paypal.sdk.util;

namespace com.paypal.sdk.core
{
	/// <summary>
	/// Manual config is used when called through COM to configure logging
	/// </summary>
	internal class ManualConfig
	{
		private const string CONFIG_FILE = "Web.config";
		private const string LOG4NET_TAG = "log4net";
		private readonly string applicationBase;

		public ManualConfig(string applicationBase)
		{
			this.applicationBase = applicationBase;
		}

		public void Run()
		{
		}

		public XmlNode ExternalFileConfigSection
		{
			get
			{
				using (StreamReader stream = GetExternalConfigFileStream())
				{
					XmlNode rootNode = Utils.CreateXmlNode(stream);
					XmlNode node = rootNode.SelectSingleNode(Config.PAYPAL_TAG);
					return node;
				}
			}
		}

		private StreamReader GetExternalConfigFileStream()
		{
			string externalConfigFilePath = Path.Combine(applicationBase, CONFIG_FILE);
			return new StreamReader(externalConfigFilePath);
		}

		private void QualifyRelativePaths(XmlElement log4netnode)
		{
			XmlNodeList fileValueNodes = log4netnode.SelectNodes("appender/file/@value");
			foreach (XmlNode fileValueNode in fileValueNodes)
			{
				if (!Path.IsPathRooted(fileValueNode.Value))
				{
					string absolutePath = Path.Combine(applicationBase, fileValueNode.Value).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
					fileValueNode.Value = absolutePath;
				}
			}
		}
	}
}
